// routes\index.js
var express = require("express");
var router = express.Router();
const jwt = require("jsonwebtoken");
const jwtConfig = require("../config/index"); // 引入私钥
const axios = require("axios");
const userModel = require("../models/index"); // 引入用户模型
const { log } = require("console");

/* GET home page */
router.get("/", (req, res) => {
  res.send({
    code: 200,
    msg: "ok",
  });
});

// 获取微信用户信息
async function fetchUserInfo(js_code) {
  const appid = "wx9f46a99ca1cf79ee";
  const secret = "71b94d4b053ee84bc01ab9801330588c";
  const grant_type = "authorization_code";
  const queryString = `appid=${appid}&secret=${secret}&js_code=${js_code}&grant_type=${grant_type}`;

  const response = await axios.get(
    `https://api.weixin.qq.com/sns/jscode2session?${queryString}`
  );
  return response.data;
}

// 登录路由
router.get("/login", async (req, res) => {
  try {
    const userInfo = await fetchUserInfo(req.query.code);
    console.log("请求腾讯api成功", userInfo);

    const { openid, session_key } = userInfo;

    const userRecord = await userModel.addUser(
      openid,
      session_key,
      userInfo.nickname,
      userInfo.avatarUrl
    );

    const token = jwt.sign(userInfo, jwtConfig.jwt.jwtSecreyKey, {
      expiresIn: jwtConfig.jwt.expressIn,
      algorithm: jwtConfig.jwt.algorithms[0],
    });
    // 获取 Token 过期时间
    const decodedToken = jwt.decode(token);
    const tokenExpireTime = decodedToken.exp; // Token 过期时间（秒）
    console.log("Token 过期时间（秒）", tokenExpireTime);

    res.send({
      code: 200,
      msg: "ok",
      data: {
        token: `Bearer ${token}`,
        userId: userRecord._id,
        tokenExpireTime: tokenExpireTime, // 返回 Token 过期时间
      },
    });
  } catch (error) {
    console.error("请求失败", error);
    res.status(500).send({ code: 500, msg: "请求失败", error: error.message });
  }
});




module.exports = router;
